#!/usr/bin/env node
// cold-start.js — starts node index.js, measures time until HTTP 200 on /, then stops it
const { spawn } = require('child_process');
const http = require('http');

function waitForUrl(url, timeoutMs) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    const iv = setInterval(() => {
      http.get(url, (res) => {
        if (res.statusCode === 200) {
          clearInterval(iv);
          resolve(Date.now() - start);
        }
      }).on('error', () => {
        if (Date.now() - start > timeoutMs) {
          clearInterval(iv);
          reject(new Error('timeout'));
        }
      });
    }, 100);
  });
}

(async ()=>{
  const proc = spawn(process.execPath, ['index.js'], { cwd: __dirname + '/..', stdio: ['ignore','pipe','pipe'] });
  let stdout = '';
  proc.stdout.on('data', d => { stdout += d.toString(); });
  proc.stderr.on('data', d => { stdout += d.toString(); });

  const url = 'http://localhost:3000/';
  const startTime = Date.now();
  try {
    const ms = await waitForUrl(url, 10000);
    console.log('cold-start (time to ready ms):', ms);
  } catch (e) {
    console.error('server did not become ready within timeout');
    proc.kill();
    process.exit(2);
  }
  proc.kill();
  process.exit(0);
})();
